package com.demon.activitychange.util;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class LaunchUtil {

    public static void startApp(Context context, String packName, String cmd, String data) {
        if (AndroidUtil.isInstall(context, packName)) {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(packName);
            if (intent != null) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("cmd", cmd);
                intent.putExtra("data", data);
                context.startActivity(intent);
            } else {
                Toast.makeText(context, "没有安装" + packName, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "没有安装" + packName, Toast.LENGTH_SHORT).show();
        }
    }

    public static void stopApp(String packName) {
        try {
            Process process = Runtime.getRuntime().exec("su");
            OutputStream out = process.getOutputStream();
            String cmd = "am force-stop " + packName + " \n";
            out.write(cmd.getBytes());
            out.flush();
            out.close();

            InputStream fis = process.getInputStream();
            //用一个读输出流类去读
            InputStreamReader isr = new InputStreamReader(fis);
            //用缓冲器读行
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            //直到读完为止 目的就是要阻塞当前的线程到命令结束的时间
            while ((line = br.readLine()) != null) {
                TraceUtil.e(line);
            }
            process = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
